package com.flanz.apache.velocity.uimocker;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple HTTP 1.0 WebServer.
 * 
 * @author cf
 * 
 */

public class WebServerThread implements Runnable {

	private static Logger LOG = LoggerFactory.getLogger(WebServerThread.class);
	private final Socket socket;
	private static int connectionCount = 0;
	private ProjectConfig projectConfig = null;

	public static synchronized void threadFinish() {
		connectionCount--;
	}

	public static synchronized void threadStart() {
		connectionCount++;
	}

	public static synchronized int getConnectionCount() {
		return connectionCount;
	}

	public WebServerThread(final Socket server,
			final ProjectConfig projectConfig) {
		this.socket = server;
		this.projectConfig = projectConfig;
	}

	@Override
	public void run() {
		try {
			try {
				OutputStream outputStream = this.socket.getOutputStream();
				InputStream inputStream = this.socket.getInputStream();
				HTTPRequestHandler.handleSocketConnection(
						projectConfig.getVM_APP_VARS(),
						projectConfig.getMimeTable(),
						projectConfig.getProjectDir()
								+ ConfigurationProvider.getInstance(null)
										.getConfiguration()
										.getString("resource_dir"),
						projectConfig.getHttpDocRoot(),
						projectConfig.getProjectMacrosFileList(), inputStream,
						outputStream);
				if (!this.socket.isClosed()) {
					this.socket.shutdownOutput();
					this.socket.close();
				}
			} catch (FileNotFoundException e) {
				LOG.error("FileNotFoundException!", e);
			} catch (IOException e) {
				LOG.error("IOException!", e);
			} catch (Exception e) {
				LOG.error("Exception!", e);
			}

		} finally {
			threadFinish();
		}

	}
}
